﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZK.Common;
using ZK.InterfaceServer;

namespace ZK.HardWareHelp
{
    /// <summary>
    /// 艾礼富的红外光栅
    /// 信科电子的458模块
    /// </summary>
    public class InfraredGrating
    {
        public static int dataNum = 0;//返回的第三位数据
        public SerialPort serialPort = null;//实例
        /// <summary>
        /// open state(打开状态-是否遮挡）
        /// </summary>
        public int res = -1;//打开和关闭的状态
        HaredWareCommonM infrared;
        /// <summary>
        /// 初始化并打开串口连接
        /// </summary>
        public InfraredGrating()
        {
            infrared = IConfig.GetSetInfrared;
            PortModel portModel = Newtonsoft
                .Json
                .JsonConvert
                .DeserializeObject<PortModel>(Newtonsoft
                .Json
                .JsonConvert
                .SerializeObject(infrared)
                ); //MyCustomConfig.InfraredConfig;
            serialPort = new SerialPort(portModel.PortName, portModel.BaudRate);
            // Open();
        }
        public InfraredGrating(string portName)
        {
            serialPort = new SerialPort(portName);
        }
        public InfraredGrating(string portName, int baudRate)
        {
            serialPort = new SerialPort(portName, baudRate);
        }
        public InfraredGrating(string portName, int baudRate, Parity parity)
        {
            serialPort = new SerialPort(portName, baudRate, parity);
        }
        public InfraredGrating(string portName, int baudRate, Parity parity, int dataBits)
        {
            serialPort = new SerialPort(portName, baudRate, parity, dataBits);
        }
        public InfraredGrating(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
        {
            serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
        }
        public InfraredGrating(Common.HaredWareCommonM config)
        {
            serialPort = new SerialPort(config.PortName, Convert.ToInt32(config.BaudRate), Parity.None, Convert.ToInt32(config.DataBits), StopBits.One);
        }
        /// <summary>
        /// 打开串口通讯
        /// </summary>
        /// <returns></returns>
        public bool Open()
        {
            bool boolRes = true;
            try
            {
                if (!serialPort.IsOpen)
                {
                    serialPort.Open();
                    serialPort.DataReceived += SerialPort_DataReceived;
                }

            }
            catch (Exception ex)
            {
                CSApiServer.AddHardWareLog(infrared.Name, 1, ex.Message);
                Common.Log4.LogManage.WriteErr("红外打开失败 " + ex.ToString());
                boolRes = false;
                Common.DelegateHelper.InfoMessageEvent.Invoke("红外打开失败");
            }
            return boolRes;
        }
        /// <summary>
        /// 读取数据委托
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Common.Log4.LogManage.WriteInfo("红外设备开始接收数据中。。。。");
            try
            {
                byte[] ReDatas1 = new byte[serialPort.BytesToRead];
                byte[] ReDatas = { 0x55, 0x01, 0x10, 0x00, 0x00, 0x00, 0x00, 0x66 };
                serialPort.Write(ReDatas, 0, ReDatas.Length);//写数据

                serialPort.Read(ReDatas1, 0, ReDatas1.Length);//读数据
                                                              //  if (ReDatas1.Length == 8 && ReDatas1[0] == 34 && (temparr[7]!= ReDatas1[7]))
                Common.Log4.LogManage.WriteInfo("红外设备接收的数据：" + string.Join(" ", ReDatas1));
                if (ReDatas1.Length >= 8 && ReDatas1[0] == 34)
                {
                    //res = ReDatas1[4];
                    DelegateHelper.InfraredGratingEvent?.Invoke(ReDatas1[4]);
                }
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteErr("红外读取数据委托" + ex.ToString());
            }
            // this.AddData(ReDatas1);//输出数据
            ////byte[] buffer = new byte[serialPort.BytesToRead];
            //byte[] buffer = new byte[8];
            //serialPort.Read(buffer, 0, buffer.Length);
            //if (buffer.Length >= 4)
            //{
            //    res = buffer[2];

            //}
        }
        /// <summary>
        /// 关闭串口连接
        /// </summary>
        /// <returns></returns>
        public bool Close()
        {
            bool res = true;
            try
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                }
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteErr("关闭串口连接 " + ex.ToString());
                res = false;
            }
            return res;
        }
    }
}
